//
//  HJLoginController.m
//  KaiChat
//
//  Created by lx on 2023/10/16.
//

#import "HJLoginController.h"
#import "HJTitleTextField.h"
#import "HJSendCodeController.h"
#import "HJMinePresent.h"
#import "QMUIButton.h"
#import "HJWebViewController.h"
#import "YYText.h"
#import "HJTimer.h"
#import "HJPositioning.h"
#import "HJSetPasswordVerifyController.h"

@interface HJLoginController ()

@property (nonatomic, weak) HJStyle1Button *loginButton;
@property (nonatomic, weak) QMUIButton *sendCodeButton;
@property (nonatomic, weak) HJTitleTextField *codeTextField;
@property (nonatomic, weak) HJTitleTextField *passwordTextField;

@property (nonatomic, strong) HJTimer *timer;
@property (nonatomic, strong) HJPositioning *positioning;
@property (nonatomic, assign) BOOL isPasswordLogin;
@property (nonatomic, weak) UIView *passwordLoginView;
@property (nonatomic, weak) UIView *codeLoginView;
@property (nonatomic, weak) QMUIButton *swichButton;

@end


@implementation HJLoginController

- (void)viewDidLoad {
    [super viewDidLoad];
 
    
    self.isPasswordLogin = YES;
    self.navigationBar.lineView.hidden = YES;
    
    UILabel *titleLabel = [UILabel lableWithSuperView:self.view font:UIFontMediumMake(20) color:UIColor.tj_333333Color title:@"Log in Kai" textAlignment:NSTextAlignmentLeft];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(KNavBarHight + 12);
        make.left.offset(leftRightMargin);
    }];
    
    UILabel *subTitleLabel = [UILabel lableWithSuperView:self.view font:UIFontMake(12) color:UIColor.tj_868391Color title:@"Take you into the era of decentralization" textAlignment:NSTextAlignmentLeft];
    subTitleLabel.numberOfLines = 0;
    [subTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(titleLabel.mas_bottom).offset(textSubTextLabelMargin);
        make.left.equalTo(titleLabel);
        make.right.inset(leftRightMargin);
    }];
    
    UIView *passwordLoginView = [UIView addToView:self.view];
    [passwordLoginView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.top.equalTo(subTitleLabel.mas_bottom).offset(40);
        make.height.offset(72);
    }];
    
    HJTitleTextField *passwordTextField = [HJTitleTextField addToView:passwordLoginView];
    passwordTextField.titleLabel.text = @"Password";
    passwordTextField.textField.placeholder = @"Enter Password";
    passwordTextField.secureTextEntry = YES;
    passwordTextField.textField.keyboardType = UIKeyboardTypeASCIICapable;
    passwordTextField.textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    [passwordTextField.textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    passwordTextField.textField.maximumTextLength = 15;
    [passwordTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.inset(leftRightMargin);
        make.top.offset(0);
        make.bottom.offset(0);
    }];
    
    QMUIButton *forgetPasswordButton = [QMUIButton buttonWithSuperView:passwordLoginView font:UIFontMake(12) color:UIColor.tj_868391Color title:@"Forget Password?"];
    [forgetPasswordButton addTarget:self action:@selector(didClickForgetPasswordButton) forControlEvents:UIControlEventTouchUpInside];
    [forgetPasswordButton sizeToFit];
    [forgetPasswordButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(passwordTextField.textField.superview);
        make.height.offset(forgetPasswordButton.tj_size.height);
        make.width.offset(forgetPasswordButton.tj_size.width);
        make.centerY.equalTo(passwordTextField.titleLabel);
    }];
    
    UIView *codeLoginView = [UIView addToView:self.view];
    codeLoginView.hidden = YES;
    [codeLoginView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.top.equalTo(subTitleLabel.mas_bottom).offset(40);
        make.height.offset(72);
    }];
    
    HJTitleTextField *codeTextField = [HJTitleTextField addToView:codeLoginView];
    codeTextField.titleLabel.text = @"Verification code";
    codeTextField.textField.placeholder = @"Enter email verification code";
    codeTextField.textField.font = UIFontMake(14);
    codeTextField.textField.maximumTextLength = 6;
    codeTextField.textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    codeTextField.textField.keyboardType = UIKeyboardTypeNumberPad;
    [codeTextField.textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    [codeTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.inset(leftRightMargin);
        make.top.offset(0);
        make.bottom.offset(0);
    }];

    QMUIButton *sendCodeButton = [QMUIButton buttonWithSuperView:codeTextField font:UIFontMake(14) color:UIColor.tj_mainColor title:@"Send"];
    [sendCodeButton setTitleColor:UIColor.tj_BEBDCAColor forState:UIControlStateDisabled];
   [sendCodeButton sizeToFit];
    CGFloat sendCodeButtonW = sendCodeButton.bounds.size.width + 10;
    [sendCodeButton addTarget:self action:@selector(didClickSendCodeButton) forControlEvents:UIControlEventTouchUpInside];
    [codeTextField.textField mas_updateConstraints:^(MASConstraintMaker *make) {
        make.right.inset(sendCodeButtonW + 15);
    }];
    [sendCodeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.inset(10);
        make.width.offset(sendCodeButtonW);
        make.top.bottom.equalTo(codeTextField.textField);
    }];
    
    
    QMUIButton *swichButton = [QMUIButton buttonWithSuperView:self.view font:UIFontMake(12) color:UIColor.tj_mainColor title:@"Switch to code login"];
    [swichButton addTarget:self action:@selector(didClickSwitchButton:) forControlEvents:UIControlEventTouchUpInside];
    [swichButton setImage:[UIImage imageNamed:@"switch_login_way"] forState:UIControlStateNormal];
    [swichButton setImagePosition:QMUIButtonImagePositionLeft];
    swichButton.spacingBetweenImageAndTitle = 4;
    [swichButton sizeToFit];
    [swichButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(codeTextField);
        make.height.offset(16);
        make.width.offset(swichButton.tj_size.width);
        make.top.equalTo(passwordLoginView.mas_bottom).inset(10);
    }];
    
    HJStyle1Button *loginButton = [HJStyle1Button buttonWithSuperView:self.view font:UIFontMediumMake(14) color:nil title:@"Log in"];
    loginButton.enabled = NO;
    [loginButton addTarget:self action:@selector(didClickLoginButton) forControlEvents:UIControlEventTouchUpInside];
    [loginButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.inset(20);
        make.height.offset(buttonHeight);
        make.top.equalTo(swichButton.mas_bottom).offset(30);
    }];

    _passwordLoginView = passwordLoginView;
    _codeLoginView = codeLoginView;
    _loginButton = loginButton;
    _codeTextField = codeTextField;
    _passwordTextField = passwordTextField;
    _swichButton = swichButton;
    _sendCodeButton = sendCodeButton;
}

- (void)startCountdown {
    TJWeakify(self);
    [self.timer start:60 countdownOngoing:^(NSInteger time) {
        weakself.sendCodeButton.enabled = NO;
        [weakself.sendCodeButton setTitle:[NSString stringWithFormat:@"%lus", time] forState:UIControlStateDisabled];
    } countdownEnd:^{
        weakself.sendCodeButton.enabled = YES;
        [weakself.sendCodeButton setTitle:@"Send" forState:UIControlStateNormal];
    }];
}

- (void)didClickForgetPasswordButton {
    HJSetPasswordVerifyController *verifyIdentityController = [[HJSetPasswordVerifyController alloc] init];
    verifyIdentityController.email = self.email;
    verifyIdentityController.type = HJSetPasswordTypeForget;
    [self.navigationController pushViewController:verifyIdentityController];
}

- (void)didClickSwitchButton:(UIButton *)button {
    _isPasswordLogin = !_isPasswordLogin;
    if (_isPasswordLogin) {
        _passwordLoginView.hidden = NO;
        _codeLoginView.hidden = YES;
        [_swichButton setTitle:@"Switch to code login" forState:UIControlStateNormal];
        [_passwordTextField.textField becomeFirstResponder];
        [self textFieldDidChange:_passwordTextField.textField];
    } else {
        _passwordLoginView.hidden = YES;
        _codeLoginView.hidden = NO;
        [_swichButton setTitle:@"Switch to password login" forState:UIControlStateNormal];
        [_codeTextField.textField becomeFirstResponder];
        [self textFieldDidChange:_codeTextField.textField];
    }
    [_swichButton sizeToFit];
    [_swichButton mas_updateConstraints:^(MASConstraintMaker *make) {
        make.width.offset(_swichButton.tj_size.width);
    }];
}

- (void)textFieldDidChange:(UITextField *)textField {
    if (_isPasswordLogin) {
        _loginButton.enabled = !isEmptyString(_passwordTextField.textField.text);
    } else {
        _loginButton.enabled = !isEmptyString(_codeTextField.textField.text);
    }
    
}
 
- (void)didClickSendCodeButton {
    [HJHUD showLoadingInView:self.view];
    [HJMinePresent sendLoginEmailCode:_email complete:^(NSError * _Nullable error) {
        if (!error) {
             [self startCountdown];
        }
    }];
    
}
 
- (void)didClickRememberPasswordButton:(UIButton *)button {
    button.selected = !button.selected;
}
 
 
- (void)didClickForgotButton {
    [self.navigationController pushViewControllerWithName:@"HJForgotPasswordController"];
}
 
- (void)didClickLoginButton {
    
    void (^complete)(NSError * _Nullable error) = ^(NSError * _Nullable error) {
        if (!error) {
            dispatch_after_main_queue(0.3, ^{
                [HJHUD showSucceedMessage:@"Login successful"];
            });
        }
    };
    
    [self.view endEditing:YES];

    if (_isPasswordLogin) {
        
        NSString *password = _passwordTextField.textField.text;
        if (isEmptyString(password)) {
            [HJHUD showErrorMessage:_passwordTextField.textField.placeholder];
            return;
        }

        [HJHUD showLoadingInView:self.view];
        [HJMinePresent loginWithAccount:self.email password:password complete:complete];
    } else {
        [HJHUD showLoadingInView:self.view];
        NSString *emailCode = _codeTextField.textField.text;
        [HJMinePresent emailCodeLoginWithEmail:_email code:emailCode complete:complete];
    }
 
}

- (HJTimer *)timer {
    if (!_timer) {
        _timer = [HJTimer timer];
    }
    return _timer;
}

- (void)setDefaultAccount {
//    eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhY2NvdW50Ijoic2NhcmxldHRsYXlzc2FyZEBnbWFpbC5jb20iLCJleHAiOjE3MDQ4OTEwODAsImlhdCI6MTcwNDI4NjI4MCwia2FpX2lkIjoiNDgxNDY4ODUyMTc1MTA5IiwidWlkIjo0ODE0Njg4NTIxNzQ5MTd9.eSJO7tARdVC8QyzQCmtG0kCf3hFKMz11grpzhyexkng
    
#ifdef DEBUG
//
//        _emailTextField.textField.text = @"semideyaubrette@gmail.com";
//        _passwordTextField.textField.text = @"a12345678!";

//    _emailTextField.textField.text = @"adermanshanna@gmail.com";
//        _passwordTextField.textField.text = @"a12345678!";
//
//    _emailTextField.textField.text = @"test1700@gmail.com";
//        _passwordTextField.textField.text = @"a12345678!";

//        _emailTextField.textField.text = @"tj23157@gmail.com";
//        _passwordTextField.textField.text = @"Xtj23157@";

//        _emailTextField.textField.text = @"xtjun@gmail.com";
//        _passwordTextField.textField.text = @"Xtj23157@0";
//
//    _emailTextField.textField.text = @"xtjun23157@gmail.com";
//    _passwordTextField.textField.text = @"Xtj23157@";
#else

#endif
    
}
 

@end
